// 221102 yan 封装自定义模块引用选择后映射操作

module.exports = Behavior({
  data:{

  },
  methods: {
    /**
     * 选择引用数据后
     * @param field 字段信息对象
     * @param val 所选引用值row_id
     * @param disVal  所选引用值显示值
     * @return {Promise<void>}
     */
    async selectReference(field,val,disVal){
      let obj = {};
      let {stockEntity} = this.data,
        isStock = stockEntity && stockEntity.is_warehouse_first;
      //出入仓模块，选择商品引用
      if (isStock && field.mainEntity === 'goods'){
        /*await Promise.all(
          [
            // this.getGoodsData(val.rowId),
            this.goodsMapping('balance_quantity',field.field_id),
            this.goodsMapping('quote_Warehouse',field.field_id),
            this.goodsMapping('balance_unit_price',field.field_id)
          ]).then(res=>{
          let goodsData = val,
            quantity = res[0],
            warehouse = res[1],
            unit_price = res[2];
          quantity.forEach(item=>{
            _obj[item] = goodsData.balance_quantity;
          });
          warehouse.forEach(item=>{
            _obj[item] = goodsData.quote_Warehouse;
            _obj[item + ';value'] = goodsData['quote_Warehouse;value'];
          });
          unit_price.forEach(item=>{
            _obj[item] = goodsData.balance_unit_price;
          });
          obj = {...obj,..._obj};

        })*/
        await this.getStockMapping(field.field_id,val).then(res=>{
          obj = {...obj,...res};
        })
      }
      if (typeof val === 'object')val = val.row_id;
      //获取映射数据
      this.getMapping({
        field_id: field.field_id,
        reference_table_id: field.mainEntity,
        row_id: val,
        table_id: this.data.entity
      },obj).then(res=>{
        let iptObj = wx.$extend(res.val);
        wx.$each(iptObj,(key,val)=>{
          if (key.indexOf(';')>=0){ delete iptObj[key]; }
        });
        this.data.inputData.entity = {...this.data.inputData.entity,...iptObj};
        let defEntity = {...this.data.defData,...res.val};
        this.setData({isEdit: true});
        this.setData({defData: defEntity});
        this.setData({isEdit: false});

        //映射后判断主表明细表映射触发修改明细表
        this.setDtlMapping(res.val);

        //映射后执行计算公式
        if (res.cal && res.cal.length) {
          this.calculate(res.cal[0]);
          /*for (let i = 0;i<res.cal.length;i++){
            this.calculate(res.cal[i]);
          } */
        }
      });

      //自定义引用商品字段为reference1_goods； 库存组装单、拆卸单、调拨单、期初库存中的引用商品字段为quote_goods
      if (field.field_id === 'reference1_goods' || field.field_id === 'quote_goods') {
        this.clearBomDetails();
        let bom = await this.getBomGoods(val),
          unit = 0,
          quantityField = field.field_id === 'quote_goods'? 'goods_unit_quantity' : 'goods_quantity',
          defEntity = this.data.defData;

        //bom表商品，填充商品单位数量
        if (bom){
          this.data.inputData.entity = {...this.data.inputData.entity,[quantityField]: bom.goods_unit_quantity};
          defEntity = {...defEntity,[quantityField]: bom.goods_unit_quantity};
          this.setData({isEdit: true});
          this.setData({defData: defEntity});
          this.setData({isEdit: false});
        }

        //221208 加载bom明细
        if (bom && bom.children && bom.children.length){
          this.data.mainQuantity = bom.goods_unit_quantity;
          this.loadBomDetails(bom.children);
        }else {
          this.data.mainQuantity = null;
          this.data.isBom = null;
        }
      }


      //仓库修改后清空商品引用--240626 yan 注释 取消商品过滤仓库
      /*if (field.field_id === 'reference1_Warehouse'){
        let {stockEntity,tableLayout} = this.data,
          isStock = stockEntity && stockEntity.is_warehouse_first;
        if (isStock){
          this.data.inputData.entity.reference1_goods = '';
          let defEntity = this.data.defData;
          defEntity.reference1_goods = '';
          defEntity['reference1_goods;value'] = '';

          this.setData({isEdit: true});
          this.clearBomDetails();
          let flag = false;
          //查找商品字段
          tableLayout.map(item=>{
            item.field && item.field.map(ite=>{
              let filedid = ite.field_id || ite.fieldName;
              if (filedid === 'reference1_goods') {
                flag = true;
                /!*let filter = ite.referenceFilterCondition;
                let obj = JSON.parse(filter);
                if (obj && obj.filters){  //引用商品字段有过滤数据
                  let flag2 = true;
                  obj.filters.forEach(ite2=>{
                    if (ite2.fieldName === 'quote_Warehouse' && ite2.operator === '='){ //已有过滤仓库则修改
                      flag2 = false;
                      ite2.value = val;
                    }
                  });
                  if (flag2){ //未有过滤仓库则添加过滤仓库
                    obj.filters.push(
                      {"type":"AND","fieldName":"quote_Warehouse","value":val,"operator":"="}
                    )
                  }
                }else { //没有过滤条件
                  obj = {"filters":[{"type":"AND","fieldName":"quote_Warehouse","value": val,"operator":"="}],"type":"AND"}
                }
                ite.referenceFilterCondition = JSON.stringify(obj);*!/
                ite.referenceFilterCondition = this.setReferenceCondition(val,'quote_Warehouse',ite.referenceFilterCondition);
              }
            })
          });
          let setObj = {defData: defEntity};
          flag && (setObj.tableLayout = tableLayout);
          this.setData(setObj);
          this.setData({isEdit: false});

        }
      }*/
      //240626 end

      //库存拆卸单中的出仓库、引用商品字段
      if (['deliver_warehouse','quote_goods'].includes(field.field_id) && this.data.entity === 'disassembly_order') {
        this.getGoodsOutPrice();
      }

    },

    /**
     * 获取字段信息
     * @param id 字段id可空，空时查全部
     * @return {Promise<any>}
     */
    getFieldInfo(id){
      let post = {
        table: this.data.entity,
        fieldname: id || ''
      };
      return new Promise(resolve => {
        wx.$post(4,'QX/PRO_select_field',post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row || [];
          resolve(data);
        })
      })
    },

    /**
     * 获取映射数据
     * @param {Object} post 提交数据对象'{
                                            field_id: 字段id,
                                            reference_table_id: 引用模块id,
                                            row_id: 所选行id,
                                            table_id: 当前模块id
                                          }'
     */
    getMapping_old(post){
      wx.$post(3,'Field_mapping/query_mapping',post).then(res=>{
        if (res.errcode != 0)return;
        let row = res.data.row || [],
          fieldArr = [],
          obj = {},
          disObj = {};
        row.forEach(item=>{
          if(!item.field_value)return;
          fieldArr.push(item.field_id);
          obj[item.field_id] = item.field_value;
          disObj[item.field_id] = item.field_value;
          disObj[item.field_id + ';value'] = item.field_value_disp;
        });
        if (row.length > 0){
          this.data.inputData.entity = {...this.data.inputData.entity,...obj};
          let defEntity = {...this.data.defData,...disObj};
          this.setData({isEdit: true});
          this.setData({defData: defEntity});
          this.setData({isEdit: false});
        }
        if (fieldArr.length > 0){
          this.getFieldInfo(fieldArr.join(',')).then(res=>{
            wx.$each(res,(i,item)=>{
              if (item.type === 'reference1' && obj[item.field_id]){
                this.getMapping({
                  field_id: item.field_id,
                  reference_table_id: item.mainEntity,
                  row_id: obj[item.field_id],
                  table_id: this.data.entity
                })
              }
            });
          })
        }
      })
    },
    getMapping(post,obj,obj2){
      return new Promise(resolve => {
        wx.$post(3,'Field_mapping/query_mapping',post).then(res=>{
          if (res.errcode != 0)return;
          let row = res.data.row || [],
            fieldArr = [];
          obj2 && wx.$each(obj2,(key,val)=>{
            if (key.indexOf(';')<0) fieldArr.push(key);
          });
          row.forEach(item=>{
            if(!item.field_value)return;
            fieldArr.push(item.field_id);
            // obj[item.field_id] = item.field_value;
            obj[item.field_id] = item.field_value;
            obj[item.field_id + ';value'] = item.field_value_disp;
          });
          /*if (row.length > 0){
            this.data.inputData.entity = {...this.data.inputData.entity,...obj};
            let defEntity = {...this.data.defData,...disObj};
            this.setData({isEdit: true});
            this.setData({defData: defEntity});
            this.setData({isEdit: false});
          }*/

          if (fieldArr.length > 0){
            this.getFieldInfo(fieldArr.join(',')).then(async res=>{
              let arr = [],
                calculateField = [];

              for (let i = 0;i<res.length;i++){
                let item = res[i];
                if (item.type === 'reference1' && obj[item.field_id]){
                  let {stockEntity} = this.data,
                    isStock = item.mainEntity === 'goods' && stockEntity && stockEntity.is_warehouse_first;

                  isStock && await this.getStockMapping(item.field_id,obj[item.field_id]).then(res=>{
                    obj = {...obj,...res};
                  })
                  arr.push(this.getMapping({
                    field_id: item.field_id,
                    reference_table_id: item.mainEntity,
                    row_id: obj[item.field_id],
                    table_id: this.data.entity
                  },obj));
                }
                if (['num','currency','percent'].includes(item.type)){
                  calculateField.push(item.field_id);
                  // this.calculate(item.field_id);
                }
              }

              if (arr.length){
                Promise.all(arr).then(res=>{
                  res.forEach(item=>{
                    calculateField = [...calculateField,...item.cal]
                  })
                  resolve({val:obj,cal: calculateField});
                })
              } else {
                resolve({val:obj,cal: calculateField});
              }
            })
          }else {
            resolve({val:obj,cal: []});
          }
        })
      })
    },

    /**
     * 获取bom表商品
     * @param id  商品行id
     * @return {Promise<string>}
     */
    async getBomGoods(id) {
      let post = {
          "quote_goods": id,
          "bom_level": 0
        },
        list = '';
      if (this.data.BomGoods[id] !== undefined){
        list = this.data.BomGoods[id];
      }else {
        await wx.$post(1,'Stock/query_bom_detailed_level',post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row[0];
          this.data.BomGoods[id] = data;
          list = data;
        });
      }
      return list;
    },

    /**
     * 获取组合件出库成本
     */
    getGoodsOutPrice: function () {
      let defEntity = this.data.defData;
      let url = 'Stock/get_goods_out_price',
        post = {
          "quote_goods": defEntity.quote_goods,
          "quote_Warehouse": defEntity.deliver_warehouse,
          "goods_quantity": defEntity.goods_unit_quantity || 0,
          "table_id": "disassembly_order"
        };
      if (post.quote_goods && post.quote_Warehouse && post.goods_quantity) {
        wx.$post(1,url,post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row[0];
          if (!data)return;
          let obj = {goods_unit_price: data.goods_unit_price,price: data.price};
          this.data.inputData.entity = {...this.data.inputData.entity,...obj};
          defEntity = {...defEntity,...obj};
          this.setData({isEdit: true});
          this.setData({defData: defEntity});
          this.setData({isEdit: false});
        });
      }

    },



    /**
     * 获取主表映射明细表
     * @param source 源表id
     * @param dest  目标表id
     */
    getDtlMapping(source,dest){
      let post = {
        "oby":"mapping_id desc",
        "page":1,
        "limit":10,
        "SearchWhere":[
          {"CompareValue":"parent_row_id","CompareWith":"destination_join_field_id","Operator":"=","or":0},
          {"CompareValue":dest,"CompareWith":"destination_table_id","Operator":"=","or":0},
          {"CompareValue":source,"CompareWith":"source_table_id","Operator":"=","or":0}
        ]};
      wx.$post(3,'Field_mapping/query_field_mapping',post).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [],
          fieldArr = [],
          {defValue,detailMapVal} = this.data,
          flag = false;
        wx.$each(data,(i,item)=>{
          fieldArr.push(item.source_field_id);

          //已有默认值-映射到明细表
          let val = defValue[item.source_field_id],
            val2 = defValue[item.source_field_id + ';value'];
          if (val) {
            let obj = {...detailMapVal[item.destination_table_id],[item.destination_field_id]: val};
            val2 && (obj[item.destination_field_id + ';value'] = val2);
            detailMapVal[item.destination_table_id] = obj;
            flag = true;
          }
        });

        this.data.dtlMapping = this.data.dtlMapping.concat(data);
        let setObj = { dtlMapField: [...this.data.dtlMapField,...fieldArr] };

        flag && (setObj.detailMapVal = detailMapVal);
        this.setData(setObj);
      })
    },
    /**
     * 主表映射明细表赋值
     * @param field (String:字段id / Object: 字段id对应值对象)
     * @param val (String: 字段值)
     * @param val2 (String: 字段显示值，引用字段)
     */
    setDtlMapping(field,val,val2){
      let mapList = this.data.dtlMapping, //映射列表
        iptDetails = this.data.inputData.details, //明细数据
        defDetail = this.data.defDetail,  //显示明细数据
        flag = false,
        flag2 = false,
        dtlMap = this.data.detailMapVal //明细映射值

      wx.$each(mapList,(i,item)=>{
        if (typeof field === 'object'){
          let keys = Object.keys(field);
          if (keys.includes(item.source_field_id) ) {
            setDtlMap(item,field[item.source_field_id],field[item.source_field_id+';value']);
          }
          return
        }
        if (item.source_field_id === field){  //源映射字段为当前字段
          setDtlMap(item,val,val2)
          /*let obj = {...dtlMap[item.destination_table_id],[item.destination_field_id]: val};
          val2 && (obj[item.destination_field_id + ';value'] = val2);
          dtlMap[item.destination_table_id] = obj;
          flag2 = true;
          wx.$each(iptDetails,(ind,ite)=>{
            if (item.destination_table_id === ite.table_id) { //目标映射模块为当前明细表
              let details = ite.entitys;

              wx.$each(details,(ind2,ite2)=>{   //循环所有明细
                ite2.entity[item.destination_field_id] = val;  //赋值映射值
                // val2 && (ite2.entity[item.destination_field_id + ';value'] = val2);
              });

              wx.$each(defDetail[ind].entitys,(ind2,ite2)=>{   //循环所有明细
                ite2.entity[item.destination_field_id] = val;  //赋值映射值
                val2 && (ite2.entity[item.destination_field_id + ';value'] = val2);
              });
              flag = true;

            }
          })*/
        }
      });

      function setDtlMap(item,val,val2) {
        let obj = {...dtlMap[item.destination_table_id],[item.destination_field_id]: val};
        val2 && (obj[item.destination_field_id + ';value'] = val2);
        dtlMap[item.destination_table_id] = obj;
        flag2 = true;
        wx.$each(iptDetails,(ind,ite)=>{
          if (item.destination_table_id === ite.table_id) { //目标映射模块为当前明细表
            let details = ite.entitys;

            wx.$each(details,(ind2,ite2)=>{   //循环所有明细
              ite2.entity[item.destination_field_id] = val;  //赋值映射值
              // val2 && (ite2.entity[item.destination_field_id + ';value'] = val2);
            });

            wx.$each(defDetail[ind].entitys,(ind2,ite2)=>{   //循环所有明细
              ite2.entity[item.destination_field_id] = val;  //赋值映射值
              val2 && (ite2.entity[item.destination_field_id + ';value'] = val2);
            });
            flag = true;

          }
        })
      }

      let obj = '';

      if (flag){
        obj = {defDetail};
      }
      if (flag2){
        obj = {...obj,detailMapVal:dtlMap};
      }
      obj && this.setData(obj);
    },

    /*加载bom表明细*/
    async loadBomDetails(details,mainNum){
      let goodsKey = '';
      //获取商品模块主显示字段
      if (this.data.goodsKey){
        goodsKey = this.data.goodsKey;
      } else {
        await this.getTableParam('goods').then(data=>{
          this.data.goodsKey = data.entity_key;
          goodsKey = data.entity_key;
        })
      }
      let {detailInfo,defDetail,inputData,entity} = this.data;
      //只有一个明细
      if (detailInfo.length === 1){
        this.data.isBom = true;
        let tableid = detailInfo[0].table_id,
          quantityField = 'goods_quantity',
          goodsField = 'reference1_goods';

        //特殊模块字段
        if (['assembly_order','disassembly_order','transfer_order','goods_opening_balance'].includes(entity)) {
          quantityField = 'goods_unit_quantity';
          goodsField = 'quote_goods';
        }

        let arr = [];
        wx.$each(details,(i,item)=>{
          arr.push(new Promise(async resolve => {
            let goodsData = '';
            await this.getGoodsDetail(item.quote_goods).then(res=>{
              goodsData = res
            });
            let goods_quantity = item.goods_unit_quantity,
              data = {row_id: 0,[quantityField]: goods_quantity,
                [goodsField]: goodsData.row_id,
                [goodsField +';value']: goodsData[goodsKey || 'goods_name'],};

            await this.getMapping({
              field_id: goodsField,
              reference_table_id: 'goods',
              row_id: goodsData.row_id,
              table_id: tableid
            },data).then();

            let iptData = wx.$extend(data);
            wx.$each(iptData,(key,val)=>{
              if (key.indexOf(';')>=0) delete iptData[key];
            });
            data.$is_bom_data = true;
            data.$bom_quantity = goods_quantity;

            if (!defDetail.length) {
              defDetail.push({
                table_id: tableid,
                entitys: [{details: [],entity:data}]
              });
              inputData.details.push({
                table_id: tableid,
                entitys: [{details: [],entity:iptData}]
              })
            }else {
              defDetail[0].entitys.push({details: [],entity:data});
              inputData.details[0].entitys.push({details: [],entity:iptData})
            }
            resolve();
          }))
        });
        Promise.all(arr).then(()=>{
          //显示明细
          this.setData({ defDetail: defDetail });
        })
      }
    },
    //获取模块参数-主显示字段等
    getTableParam(tableid) {
      let url = 'Entity_param/query_entity_param',
        post = {
          table_id: tableid
        };

      return new Promise(function (resolve) {
        wx.$post(3,url,post).then(res=>{
          if (res.errcode != 0)return;
          resolve(res.data.row[0]);
        })
      }).then();
    },
    //获取商品具体信息
    getGoodsDetail (rowid) {
      let This = this,
        url = 'DynamicQuery/query_dynamic_v3',
        post = {
          "oby":"goods.row_id desc",
          "table_id":"goods",
          "page":1,
          "limit":1,
          "SearchWhere":{
            "type": "and",
            "filters" : [
              {
                "CompareValue": rowid,
                "CompareWith": "goods.row_id",
                "Operator": "=",
                "or": 0
              }
            ]
          }
        },
        resp = '',
        goodsDetails = this.data.goodsDetails || {};
      return new Promise(resolve => {
        if (goodsDetails[rowid]){
          resp = goodsDetails[rowid];
          resolve(resp);
        } else {
          wx.$post(3,url,post).then(res=>{
            if (res.errcode != 0)return;
            let data = res.data.row[0];
            if (data){
              goodsDetails[rowid] = data;
              resp = data;
              this.data.goodsDetails = goodsDetails;
              resolve(resp);
            }
          })
        }
      })
    },
    //获取bom表商品映射值
    getBomMapping(rowid,tr,tableid,entityField,sourceTable,obj) {  //引用行id，赋值目标位置行，引用模块，关联字段，目标模块
      //rowid,wrap,tableid

      let url = 'Field_mapping/query_mapping',
        data = {"table_id":sourceTable,"reference_table_id": tableid,"row_id": rowid, 'field_id': entityField},
        wrap = tr.find('.attribute-item');
      return new Promise(resolve => {
        wx.$post(3,url,data).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row,
            fieldArr = {};
          wx.$each(data,(i,item)=>{
            obj[item.field_id] = item.field_value;
            obj[item.field_id + ';value'] = item.field_value_disp;
            fieldArr[item.field_id] = item.field_value;
          });

          if (!Object.keys(fieldArr).length){
            $.each(fieldArr,function (key,val) {
              let dom = tr.find('.attribute-item.j-detail_' + key),
                type = dom.data('type'),
                refBtn = dom.find('.reference-btn'),
                mainEntity = refBtn.attr('mainentity');
              if (dom.length > 0 && type === 'reference1'){
                getBomMapping(val,tr,mainEntity,key,sourceTable)
              }
            })
          }
        })
      })
    },

    //清空已输入bom表明细
    clearBomDetails(){
      let {defDetail,inputData,isBom} = this.data;
      if (!isBom)return;
      let details = defDetail[0].entitys,
        inputDetails = inputData.details[0].entitys;
      let i = details.length;
      while (i--) {
        if (details[i].entity.$is_bom_data) {
          details.splice(i,1);
          inputDetails.splice(i,1);
        }
      }
      this.setData({ defDetail: defDetail });
    },

    // 根据bom表商品数量关系触发联动修改数量
    handleQuantity(num){
      let {mainQuantity,isBom,defDetail,inputData,entity} = this.data;
      if (!isBom)return;
      let details = defDetail[0].entitys,
        inputDetails = inputData.details[0].entitys,
        field = 'goods_quantity';

      //特殊模块字段
      if (['assembly_order','disassembly_order','transfer_order','goods_opening_balance'].includes(entity)) field = 'goods_unit_quantity';
      wx.$each(details,(i,item)=>{
        let data = item.entity;
        if (data.$is_bom_data) {
          let quantity = Number(num*Number(data.$bom_quantity)/Number(mainQuantity || 1)).toFixed(0);
          data[field] = quantity;
          inputDetails[i].entity[field] = quantity;
        }
      });
      this.setData({ defDetail: defDetail });
    },

    //获取商品库存余额表映射
    goodsMapping(source_field_id,dest_join_field_id){
      let {entity} = this.data,
        url = 'Field_mapping/query_field_mapping',
        post = {
          "page":1,
          "limit":10,
          "oby":"mapping_id desc",
          "SearchWhere":[
            {"CompareWith":"source_field_id","Operator":"=","CompareValue":source_field_id,"or":0},
            {"CompareWith":"destination_table_id","Operator":"=","CompareValue":entity,"or":0},
            {"CompareWith":"destination_join_field_id","Operator":"=","CompareValue": dest_join_field_id,"or":0},
            {"CompareWith":"source_table_id","Operator":"=","CompareValue":'goods',"or":0}
          ]
        };
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res=>{
          let data = res.data.row || [],
            arr = [];
          data.forEach(item=>{
            arr.push(item.destination_field_id)
          })
          resolve(arr);
        })
      })
    },

    //获取商品库存余额数据
    getGoodsData(id){
      let url = 'DynamicQuery/query_dynamic_v3',
        post = {
        "table_id":"v_goods_balance",
          "oby":"v_goods_balance.row_id desc",
          "page":1,
          "limit":1,
          "SearchWhere":{"type":"and","filters":[{"CompareWith":"v_goods_balance.row_id","Operator":"=","CompareValue":id,"or":0}]}
      };
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res=>{
          if (res.errcode != 0)return;
          resolve(res.data.row[0]);
        })
      })
    },

    //获取库存映射
    getStockMapping(fieldid,val){
      let arr = [
        // this.getGoodsData(val.rowId),
        this.goodsMapping('balance_quantity',fieldid),
        this.goodsMapping('quote_Warehouse',fieldid),
        this.goodsMapping('balance_unit_price',fieldid)
      ];
      if (typeof val !== "object"){
        arr.push(this.getGoodsData(val))
      }
      return new Promise(resolve => {
        Promise.all(arr).then(res=>{
          let goodsData = res[3] || val,
            quantity = res[0],
            warehouse = res[1],
            unit_price = res[2],
            obj = {};
          quantity.forEach(item=>{
            obj[item] = goodsData.balance_quantity;
          });
          warehouse.forEach(item=>{
            obj[item] = goodsData.quote_Warehouse;
            obj[item + ';value'] = goodsData['quote_Warehouse;value'];
          });
          unit_price.forEach(item=>{
            obj[item] = goodsData.balance_unit_price;
          });

          resolve(obj)

        })
      })
    }
  }
})
